﻿using Abp;
using Abp.Application.Services;
using Abp.UI;
using CheryABP.ApiAttribute;
using CheryABP.Common;
using CheryABP.Extensions;
using CheryABP.SystemSetitng;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Reflection;
using System.Threading.Tasks;

namespace CheryABP
{
    /// <summary>
    /// 基础接口
    /// </summary>
    public class CheryServiceBase : ApplicationService
    {
        /// <summary>
        /// 登录人信息
        /// </summary>
        protected system_login AdminInfo;
        /// <summary>
        /// 
        /// </summary>
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        public CheryServiceBase(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
            ValidateSession();
            _httpContextAccessor.HttpContext.Response.Redirect("/404.html");
            return;
        }



        /// <summary>
        /// 校验SESSION
        /// </summary>
        protected void ValidateSession()
        {
            try
            {
                var context = _httpContextAccessor.HttpContext;
                var path = context.Request.Path;
                var _session = context.Session;
                if (path.HasValue && path.Value.Contains("/api/services/app/"))
                {
                    AdminInfo = AbpSessionExtension.GetObjectFromJson<system_login>(_session, DTKeys.SESSION_ADMIN_INFO);
                    if (AdminInfo == null)
                    {
                        //查找方法上的特性是否是忽略验证的特性
                        string funcName = path.Value.Substring(path.Value.LastIndexOf('/') + 1);
                        var method = GetType().GetMethod(funcName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
                        if (method.GetCustomAttribute<NonAuthorizationAttribute>() == null)
                        {
                            _httpContextAccessor.HttpContext.Response.Redirect("/404.html");
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(ex.Message);
            }
        }

    }
}
